#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
将新闻日报 Markdown 文件转换为美观的 HTML 页面
支持深色/浅色模式切换，使用现代简洁设计
"""

import markdown
import os
import datetime
import webbrowser
import glob
from jinja2 import Template

# HTML 模板
HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <style>
        :root {
            --bg-color: #ffffff;
            --text-color: #333333;
            --link-color: #0066cc;
            --border-color: #e0e0e0;
            --header-bg: #f8f8f8;
            --code-bg: #f5f5f5;
            --shadow-color: rgba(0, 0, 0, 0.1);
        }

        .dark-mode {
            --bg-color: #1e1e1e;
            --text-color: #e0e0e0;
            --link-color: #4da6ff;
            --border-color: #444444;
            --header-bg: #2d2d2d;
            --code-bg: #2d2d2d;
            --shadow-color: rgba(0, 0, 0, 0.3);
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 
                         'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            line-height: 1.6;
            margin: 0;
            padding: 0;
            transition: background-color 0.3s, color 0.3s;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        header {
            text-align: center;
            padding: 20px 0;
            margin-bottom: 30px;
            border-bottom: 1px solid var(--border-color);
            background-color: var(--header-bg);
        }

        h1, h2, h3 {
            color: var(--text-color);
        }

        h1 {
            font-size: 2.2em;
            margin-bottom: 10px;
        }

        h2 {
            font-size: 1.8em;
            margin-top: 30px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--border-color);
        }

        h3 {
            font-size: 1.4em;
            margin-top: 25px;
            margin-bottom: 15px;
        }

        a {
            color: var(--link-color);
            text-decoration: none;
        }

        a:hover {
            text-decoration: underline;
        }

        p {
            margin-bottom: 1.2em;
            text-align: justify;
        }

        ul {
            padding-left: 20px;
        }

        li {
            margin-bottom: 8px;
        }

        .timestamp {
            text-align: center;
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid var(--border-color);
            color: var(--text-color);
            font-size: 0.9em;
        }

        .theme-toggle {
            position: fixed;
            top: 20px;
            right: 20px;
            background: var(--header-bg);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            padding: 8px 15px;
            cursor: pointer;
            font-size: 0.9em;
            box-shadow: 0 2px 5px var(--shadow-color);
            z-index: 1000;
        }

        .toc {
            background-color: var(--header-bg);
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            border: 1px solid var(--border-color);
        }

        .toc h2 {
            margin-top: 0;
            border-bottom: none;
        }

        .toc ul {
            list-style-type: none;
            padding-left: 0;
        }

        .toc li {
            margin-bottom: 10px;
        }

        .toc a {
            text-decoration: none;
        }

        hr {
            border: 0;
            height: 1px;
            background: var(--border-color);
            margin: 30px 0;
        }

        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            h1 {
                font-size: 1.8em;
            }
            
            h2 {
                font-size: 1.5em;
            }
            
            h3 {
                font-size: 1.2em;
            }
        }
    </style>
</head>
<body>
    <div class="theme-toggle" onclick="toggleTheme()">🌓 切换主题</div>
    
    <div class="container">
        <header>
            <h1>{{ title }}</h1>
        </header>
        
        <nav class="toc">
            <h2>目录</h2>
            <ul>
                <li><a href="#summary">今日导览摘要</a></li>
                {% for category in categories %}
                <li><a href="#{{ category.id }}">{{ category.name }}</a></li>
                {% endfor %}
            </ul>
        </nav>
        
        {{ content|safe }}
        
        <div class="timestamp">
            页面生成时间: {{ timestamp }}
        </div>
    </div>

    <script>
        // 检查用户偏好的主题
        function checkPreferredTheme() {
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            const savedTheme = localStorage.getItem('theme');
            
            if (savedTheme === 'dark' || (prefersDark && savedTheme !== 'light')) {
                document.body.classList.add('dark-mode');
            }
        }
        
        // 切换主题
        function toggleTheme() {
            const isDark = document.body.classList.toggle('dark-mode');
            localStorage.setItem('theme', isDark ? 'dark' : 'light');
        }
        
        // 页面加载时检查主题
        checkPreferredTheme();
        
        // 添加平滑滚动
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function(e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    window.scrollTo({
                        top: target.offsetTop - 20,
                        behavior: 'smooth'
                    });
                }
            });
        });
    </script>
</body>
</html>"""

# 用于邮件的简化HTML模板（无JavaScript，适合邮件客户端）
EMAIL_HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 
                         'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: #ffffff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        header {
            text-align: center;
            padding: 20px 0;
            margin-bottom: 30px;
            border-bottom: 1px solid #eee;
        }

        h1, h2, h3 {
            color: #333;
        }

        h1 {
            font-size: 2.2em;
            margin-bottom: 10px;
        }

        h2 {
            font-size: 1.8em;
            margin-top: 30px;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
        }

        h3 {
            font-size: 1.4em;
            margin-top: 25px;
            margin-bottom: 15px;
        }

        a {
            color: #0066cc;
            text-decoration: none;
        }

        a:hover {
            text-decoration: underline;
        }

        p {
            margin-bottom: 1.2em;
            text-align: justify;
        }

        ul {
            padding-left: 20px;
        }

        li {
            margin-bottom: 8px;
        }

        .timestamp {
            text-align: center;
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #eee;
            color: #666;
            font-size: 0.9em;
        }

        .toc {
            background-color: #f8f8f8;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            border: 1px solid #eee;
        }

        .toc h2 {
            margin-top: 0;
            border-bottom: none;
        }

        .toc ul {
            list-style-type: none;
            padding-left: 0;
        }

        .toc li {
            margin-bottom: 10px;
        }

        .toc a {
            text-decoration: none;
        }

        hr {
            border: 0;
            height: 1px;
            background: #eee;
            margin: 30px 0;
        }

        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            h1 {
                font-size: 1.8em;
            }
            
            h2 {
                font-size: 1.5em;
            }
            
            h3 {
                font-size: 1.2em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>{{ title }}</h1>
        </header>
        
        <nav class="toc">
            <h2>目录</h2>
            <ul>
                <li><a href="#summary">今日导览摘要</a></li>
                {% for category in categories %}
                <li><a href="#{{ category.id }}">{{ category.name }}</a></li>
                {% endfor %}
            </ul>
        </nav>
        
        {{ content|safe }}
        
        <div class="timestamp">
            页面生成时间: {{ timestamp }}
        </div>
    </div>
</body>
</html>"""

def parse_markdown_content(md_content):
    """解析 Markdown 内容，提取分类信息"""
    lines = md_content.split('\n')
    categories = []
    
    for line in lines:
        if line.startswith('## ') and '今日导览摘要' not in line:
            category_name = line[3:].strip()
            # 创建一个简单的ID（用于锚点链接）
            category_id = category_name.strip().replace(' ', '-').lower()
            categories.append({
                'name': category_name,
                'id': category_id
            })
    
    return categories

def convert_md_to_html(md_file_path, for_email=False):
    """将 Markdown 文件转换为 HTML"""
    # 获取文件名（不含扩展名）用于标题
    base_name = os.path.splitext(os.path.basename(md_file_path))[0]
    title = base_name.replace('_', ' ')
    
    # 读取 Markdown 文件内容
    with open(md_file_path, 'r', encoding='utf-8') as f:
        md_content = f.read()
    
    # 解析分类信息用于目录
    categories = parse_markdown_content(md_content)
    
    # 转换 Markdown 为 HTML
    html_content = markdown.markdown(md_content, extensions=['fenced_code', 'tables'])
    
    # 根据用途选择模板
    template_str = EMAIL_HTML_TEMPLATE if for_email else HTML_TEMPLATE
    template = Template(template_str)
    
    html_output = template.render(
        title=title,
        content=html_content,
        categories=categories,
        timestamp=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    )
    
    # 保存为 HTML 文件
    html_file_path = os.path.splitext(md_file_path)[0] + '.html'
    with open(html_file_path, 'w', encoding='utf-8') as f:
        f.write(html_output)
    
    print(f"HTML 页面已生成: {html_file_path}")
    return html_file_path

def convert_md_to_html_for_email(md_file_path):
    """将 Markdown 文件转换为适合邮件的 HTML"""
    return convert_md_to_html(md_file_path, for_email=True)

def open_in_browser(html_file_path):
    """在浏览器中打开 HTML 文件"""
    webbrowser.open('file://' + os.path.abspath(html_file_path))
    print(f"已在浏览器中打开: {html_file_path}")

def main():
    """主函数"""
    # 查找当前目录下最新的 news_report_*.md 文件
    md_files = glob.glob("news_report_*.md")
    if not md_files:
        print("未找到新闻报告 Markdown 文件")
        return
    
    # 选择最新的文件
    latest_md = max(md_files, key=os.path.getctime)
    print(f"找到最新的新闻报告: {latest_md}")
    
    # 转换为 HTML
    html_file = convert_md_to_html(latest_md)
    
    # 在浏览器中打开
    open_in_browser(html_file)

if __name__ == "__main__":
    main()